package cn.lili.controller.goods;

import cn.lili.common.enums.ResultUtil;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.OperationalJudgment;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.goods.entity.dos.GoodsImgDict;
import cn.lili.modules.goods.entity.dos.GoodsSku;
import cn.lili.modules.goods.entity.dto.GoodsOperationDTO;
import cn.lili.modules.goods.entity.dto.GoodsSearchParams;
import cn.lili.modules.goods.entity.dto.GoodsSkuStockDTO;
import cn.lili.modules.goods.entity.enums.GoodsStatusEnum;
import cn.lili.modules.goods.entity.vos.*;
import cn.lili.modules.goods.service.*;
import cn.lili.modules.store.entity.dos.StoreDetail;
import cn.lili.modules.store.service.StoreDetailService;
import cn.lili.modules.whitebar.entity.vo.CommissionSearchParams;
import cn.lili.modules.whitebar.entity.vo.CommissionVO;
import cn.lili.modules.whitebar.service.CommissionService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.springframework.web.multipart.MultipartFile;

/**
 * 店铺端,商品接口
 *
 * @author pikachu
 * @since 2020-02-23 15:18:56
 */
@RestController
@Api(tags = "店铺端,商品接口")
@RequestMapping("/store/goods")
public class GoodsStoreController {

	/**
	 * 商品
	 */
	@Autowired
	private GoodsService goodsService;
	/**
	 * 商品sku
	 */
	@Autowired
	private GoodsSkuService goodsSkuService;
	@Autowired
	private CategoryService categoryService;

	/**
	 * 店铺详情
	 */
	@Autowired
	private StoreDetailService storeDetailService;
	/**
	 * 佣金管理
	 */
	@Autowired
	private CommissionService commissionService;
	/**
	 * 商品图片信息维护
	 */
	@Autowired
	private GoodsImgDictService goodsImgDictService;

	@ApiOperation(value = "分页获取商品列表")
	@RequestMapping(value = "/list")
	public ResultMessage<IPage<GoodsVO>> getByPage(GoodsSearchParams goodsSearchParams) {
		// 获取当前登录商家账号
		String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId();
		goodsSearchParams.setStoreId(storeId);
		IPage<GoodsVO> goodsVOIPage = goodsService.queryByParams(goodsSearchParams);
		List<GoodsVO> records = goodsVOIPage.getRecords();
		for (GoodsVO goodsVo : records) {
			String categoryPath = goodsVo.getCategoryPath();
			if (StringUtils.isNotEmpty(categoryPath)) {
				String[] split = categoryPath.split(",");
				goodsVo.setCategoryName(categoryService.getCategoryNameByIds(Arrays.asList(split)));
			}
		}
		return ResultUtil.data(goodsVOIPage);
	}

	@ApiOperation(value = "分页获取商品Sku列表")
	@RequestMapping(value = "/sku/list")
	public ResultMessage<IPage<GoodsSku>> getSkuByPage(GoodsSearchParams goodsSearchParams) {
		// 获取当前登录商家账号
		String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId();
		goodsSearchParams.setStoreId(storeId);
		return ResultUtil.data(goodsSkuService.getGoodsSkuByPage(goodsSearchParams));
	}

	@ApiOperation(value = "分页获取库存告警商品列表")
	@RequestMapping(value = "/list/stock")
	public ResultMessage<StockWarningVO> getWarningStockByPage(GoodsSearchParams goodsSearchParams) {
		// 获取当前登录商家账号
		String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId();
		StoreDetail storeDetail = OperationalJudgment.judgment(storeDetailService.getStoreDetail(storeId));
		Integer stockWarnNum = storeDetail.getStockWarning();
		goodsSearchParams.setStoreId(storeId);
		goodsSearchParams.setLeQuantity(stockWarnNum);
		goodsSearchParams.setMarketEnable(GoodsStatusEnum.UPPER.name());
		IPage<GoodsSku> goodsSku = goodsSkuService.getGoodsSkuByPage(goodsSearchParams);
		StockWarningVO stockWarning = new StockWarningVO(stockWarnNum, goodsSku);
		return ResultUtil.data(stockWarning);
	}

	@ApiOperation(value = "通过id获取")
	@RequestMapping(value = "/get/{id}")
	public ResultMessage<GoodsVO> get(@PathVariable String id) {
		GoodsVO goods = OperationalJudgment.judgment(goodsService.getGoodsVO(id));
		return ResultUtil.data(goods);
	}

	@ApiOperation(value = "新增商品")
	@RequestMapping(value = "/create", consumes = "application/json", produces = "application/json")
	public ResultMessage<GoodsOperationDTO> save(@Valid @RequestBody GoodsOperationDTO goodsOperationDTO) {
		goodsService.addGoods(goodsOperationDTO);
		return ResultUtil.success();
	}

	@ApiOperation(value = "修改商品")
	@PutMapping(value = "/update/{goodsId}", consumes = "application/json", produces = "application/json")
	public ResultMessage<GoodsOperationDTO> update(@RequestBody GoodsOperationDTO goodsOperationDTO,
			@PathVariable String goodsId) {
		goodsService.editGoods(goodsOperationDTO, goodsId);
		return ResultUtil.success();
	}

	@ApiOperation(value = "下架商品", notes = "下架商品时使用")
	@ApiImplicitParam(name = "goodsId", value = "商品ID", required = true, paramType = "query", allowMultiple = true)
	@PutMapping(value = "/under")
	public ResultMessage<Object> underGoods(@RequestParam List<String> goodsId) {

		goodsService.updateGoodsMarketAble(goodsId, GoodsStatusEnum.DOWN, "商家下架");
		return ResultUtil.success();
	}

	@ApiOperation(value = "上架商品", notes = "上架商品时使用")
	@PutMapping(value = "/up")
	@ApiImplicitParam(name = "goodsId", value = "商品ID", required = true, paramType = "query", allowMultiple = true)
	public ResultMessage<Object> unpGoods(@RequestParam List<String> goodsId) {
		goodsService.updateGoodsMarketAble(goodsId, GoodsStatusEnum.UPPER, "");
		return ResultUtil.success();
	}

	@ApiOperation(value = "商品排序", notes = "商品排序")
	@PutMapping(value = "/sortGoods/{goodsId}")
	public ResultMessage<Object> sortGoods(@PathVariable String goodsId, int num) {
		return ResultUtil.data(goodsService.updateSortGoods(goodsId, num));
	}

	@ApiOperation(value = "删除商品")
	@PutMapping(value = "/delete")
	@ApiImplicitParam(name = "goodsId", value = "商品ID", required = true, paramType = "query", allowMultiple = true)
	public ResultMessage<Object> deleteGoods(@RequestParam List<String> goodsId) {
		goodsService.deleteGoods(goodsId);
		return ResultUtil.success();
	}

	@ApiOperation(value = "设置商品运费模板")
	@PutMapping(value = "/freight")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "goodsId", value = "商品ID", required = true, paramType = "query", allowMultiple = true),
			@ApiImplicitParam(name = "templateId", value = "运费模板ID", required = true, paramType = "query")})
	public ResultMessage<Object> freight(@RequestParam List<String> goodsId, @RequestParam String templateId) {
		goodsService.freight(goodsId, templateId);
		return ResultUtil.success();
	}

	@ApiOperation(value = "根据goodsId分页获取商品规格列表")
	@RequestMapping(value = "/sku/{goodsId}/list")
	public ResultMessage<List<GoodsSkuVO>> getSkuByList(@PathVariable String goodsId) {
		String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId();
		return ResultUtil.data(goodsSkuService.getGoodsSkuVOList(goodsSkuService.list(new LambdaQueryWrapper<GoodsSku>()
				.eq(GoodsSku::getGoodsId, goodsId).eq(GoodsSku::getStoreId, storeId))));
	}

	@ApiOperation(value = "修改商品库存")
	@PutMapping(value = "/update/stocks", consumes = "application/json")
	public ResultMessage<Object> updateStocks(@RequestBody List<GoodsSkuStockDTO> updateStockList) {
		String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId();
		// 获取商品skuId集合
		List<String> goodsSkuIds = updateStockList.stream().map(GoodsSkuStockDTO::getSkuId)
				.collect(Collectors.toList());
		// 根据skuId集合查询商品信息
		List<GoodsSku> goodsSkuList = goodsSkuService.list(
				new LambdaQueryWrapper<GoodsSku>().in(GoodsSku::getId, goodsSkuIds).eq(GoodsSku::getStoreId, storeId));
		// 过滤不符合当前店铺的商品
		List<String> filterGoodsSkuIds = goodsSkuList.stream().map(GoodsSku::getId).collect(Collectors.toList());
		List<GoodsSkuStockDTO> collect = updateStockList.stream().filter(i -> filterGoodsSkuIds.contains(i.getSkuId()))
				.collect(Collectors.toList());
		goodsSkuService.updateStocks(collect);
		return ResultUtil.success();
	}

	@ApiOperation(value = "佣金管理")
	@ApiImplicitParams({@ApiImplicitParam(name = "userName", value = "名称", paramType = "query")})
	@RequestMapping(value = "/getByPage")
	public ResultMessage<IPage<CommissionVO>> getByPage(CommissionSearchParams commissionSearchParams) {

		return ResultUtil.data(commissionService.commissionPage(commissionSearchParams));
	}

	@ApiOperation(value = "商品图片批量上传(配合商品excel导入)")
	@RequestMapping(value = "/batchImg", consumes = "application/json")
	public ResultMessage<Object> batchImg(@RequestBody List<GoodsImgDict> goodsImgDicts) {
		String storeId = Objects.requireNonNull(UserContext.getCurrentUser()).getStoreId();
		goodsImgDicts.forEach(goodsImgDict -> goodsImgDict.setStoreId(storeId));
		goodsImgDictService.saveBatch(goodsImgDicts);
		return ResultUtil.success();
	}

	@ApiOperation(value = "批量导入商品模板下载")
	@RequestMapping("/importBatchTemplate")
	public void importBatchTemplate(HttpServletResponse response) {
		goodsService.importBatchTemplate(response);
	}

	// @ApiOperation(value = "批量导入商品")
	// @RequestMapping("/importBatch")
	// public ResultMessage<Object> importBatch(MultipartFile file) throws Exception
	// {
	// goodsService.importBatch(file);
	// return ResultUtil.success();
	// }

	@ApiOperation(value = "批量导入商品")
	@RequestMapping("/importBatch")
	public ResultMessage<List<ImportResult>> importBatch(MultipartFile file) throws Exception {
		List<ImportResult> importResultList = goodsService.importBatchNew(file);
		return ResultUtil.data(importResultList);
	}

	@ApiOperation(value = "通过店铺查询店铺下的商品")
	@RequestMapping("/storeId")
	public ResultMessage<IPage<GoodsVO>> getGoodsByStoreId(PageVO page, String goodsName, String activityId,
			String shopCategoryPath) {
		AuthUser authUser = Objects.requireNonNull(UserContext.getCurrentUser());
		IPage<GoodsVO> goodsVOList = goodsService.getGoodsByStoreId(page, authUser.getStoreId(), goodsName, activityId,
				shopCategoryPath);
		return ResultUtil.data(goodsVOList);
	}
}
